﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;

namespace PBO.Game.BattleLog
{
    public class BattleLogger : ILogBuilder, IEnumerable<string>
    {

        #region IBattleLogger

        private const int WAIT_TIME = 180;
        public Color LastColor { get; protected set; }
        public string LastText { get; protected set; }

        private List<string> logList = new List<string>();

        public event Action<string, Color> LogAdded;

        protected void OnLogAdded(string text, Color color)
        {
            if (LogAdded != null)
            {
                AppendLog(text);
                this.LastColor = color;
                this.LastText = text;
                Thread.Sleep(WAIT_TIME);
                LogAdded(text, color);
            }
        }

        public void AppendLog(string text)
        {
            this.logList.Add(text);
        }

        public void AppendText(string text)
        {
            AppendText(text, Color.Black);
        }

        public void AppendText(string text, Color color)
        {
            OnLogAdded(text, color);
        }

        public void AppendMsg(string key, params object[] items)
        {
            string msg = string.Empty;
            bool fail = false;

            int argb = PBO.Data.SQLite.SQLiteHelper.GetMsgArgb(key);
            var color = Color.FromArgb(argb);

            try
            {
                msg = LogHelper.BuildLog(key, items);
                fail = string.IsNullOrEmpty(msg);
            }
            catch
            {
                fail = true;
            }

            if (fail)
            {
                color = Color.Red;
                msg = string.Format("error key : {0}", key);
            }

            OnLogAdded(msg, color);
        }

        #endregion

        #region IEnumerator

        public IEnumerator<string> GetEnumerator()
        {
            return logList.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return logList.GetEnumerator();
        }

        #endregion

    }
}
